﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using HealthManagement.Model;
using HealthManagement.Data.Service;
using HealthManagement.Data.Model;
using Telerik.Windows.Controls.Charting;
using System.Data;
using System.Threading;

namespace HealthManagement.View
{
    /// <summary>
    /// Index.xaml 的交互逻辑
    /// </summary>
    public partial class Index : Page
    {
        
        IList<UserModel> users;
        UserService ser = new UserService();

        public Index()
        {
            InitializeComponent();

            
            //rc.DefaultView.ChartLegend.Style = Application.Current.FindResource("CustomLegendItemStyle") as Style;
            rc.DefaultView.ChartLegend.Foreground = Application.Current.FindResource("text") as Brush;
            rc.DefaultView.ChartLegend.Background = new SolidColorBrush(Colors.Transparent);
            rc.DefaultView.ChartLegend.LegendItemStyle = Application.Current.FindResource("ChartLegendItemStyle") as Style;
            //rc.DefaultView.ChartArea.AxisX.Visibility = Visibility.Collapsed;
            rc.DefaultView.ChartArea.AxisX.AxisStyles.ItemLabelStyle = Application.Current.FindResource("XItemLabelStyle") as Style;
            rc.DefaultView.ChartArea.AxisX.DefaultLabelFormat = "#VAL{yy年M月}";
            rc.DefaultView.ChartArea.AxisX.Step = 1;
            rc.DefaultView.ChartArea.AxisY.AxisStyles.GridLineStyle = Application.Current.FindResource("YGridLineStyle") as Style;
            rc.DefaultView.ChartArea.AxisY.AxisStyles.ItemLabelStyle = Application.Current.FindResource("XItemLabelStyle") as Style;
            rc.DefaultView.ChartArea.AxisY.ExtendDirection = AxisExtendDirection.Up;
            rc.DefaultView.ChartArea.AxisY.MinorTicksVisibility = Visibility.Collapsed;
            rc.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Collapsed;
            rc.DefaultView.ChartArea.AxisY.MajorTicksVisibility = Visibility.Collapsed;
            rc.DefaultView.ChartArea.AxisY.MajorGridLinesVisibility = Visibility.Visible;
            rc.DefaultView.ChartArea.AxisY.PlotAreaAxisVisibility = Visibility.Collapsed;


            
            InitTotalINfo();
            //bug? shit mysql
            DataSet ds = ser.GetLastAndInvalid();
            InitLastMeasured(ds.Tables[0]);
            InitInvalidMeasured(ds.Tables[1]);


            //InitLastMeasured();
            //InitInvalidMeasured();

           
        }


        private void InitTotalINfo()
        {
            DataSet dset = ser.GetMeasuredUserList();


            int[] totalCount = new int[5];
            int[] invalidCount = new int[5];
            int[] validCount = new int[5];

            List<MeasureData>[] lists = new List<MeasureData>[5];
            List<List<ChartValue>> values = new List<List<ChartValue>>();
            values.Add(new List<ChartValue>());
            values.Add(new List<ChartValue>());

            for (int i = 0; i < 5; i++)
            {
                lists[i] = dset.Tables[i].AsEnumerable().Select(c =>
                    new MeasureData
                    {
                        UserId = c.Field<string>("userid"),
                        UserName = c.Field<string>("username"),
                        MeasureType = c.Field<string>("measureType"),
                        MeasureDate = c.Field<string>("measureDate"),
                        MeasureValue = c.Field<decimal>("measureValue"),
                        Max = c.Field<decimal>("max"),
                        Min = c.Field<decimal>("min")
                    }).ToList();

                totalCount[i] = lists[i].Select(c => c.UserId).Distinct().Count();
                invalidCount[i] = lists[i].Where(c => c.MeasureValue < c.Min || c.MeasureValue > c.Max)
                   .Select(c => c.UserId).Distinct().Count();
                validCount[i] = totalCount[i] - invalidCount[i];
                values[0].Add(new ChartValue() { Value = validCount[i], Time = DateTime.Now.AddMonths(-4+i) });
                values[1].Add(new ChartValue() { Value = invalidCount[i], Time = DateTime.Now.AddMonths(-4+i) });
            }

           
           
            IndexInfoModel info = new IndexInfoModel();
            info.TotalCount = totalCount[4];
            info.NormalCount = validCount[4];
            info.AlarmCount = invalidCount[4];
            this.DataContext = info;

            #region chart
            rc.SeriesMappings.Clear();
            rc.ItemsSource = null;
            rc.DefaultView.ChartArea.EnableAnimations = true;
            rc.DefaultView.ChartLegend.Header = "最近5个月数据对比";

            SeriesMapping mapping = new SeriesMapping();
            mapping.LegendLabel = "正常数";
            mapping.CollectionIndex = 0;
            SplineSeriesDefinition def = new SplineSeriesDefinition();
            def.ItemLabelFormat = "0.#";
            def.ShowItemLabels = true;
            def.Appearance = new SeriesAppearanceSettings { Fill = Application.Current.FindResource("actual") as Brush };
            mapping.SeriesDefinition = def;
            mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue ));
            mapping.ItemMappings.Add(new ItemMapping("Time", DataPointMember.XCategory));
            rc.SeriesMappings.Add(mapping);

            mapping = new SeriesMapping();
            mapping.LegendLabel = "异常数";
            mapping.CollectionIndex = 1;
            def = new SplineSeriesDefinition();
            def.ItemLabelFormat = "0.#";
            def.ShowItemLabels = true;
            def.Appearance = new SeriesAppearanceSettings { Fill = Application.Current.FindResource("actual") as Brush };
            mapping.SeriesDefinition = def;
             mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue ));
             mapping.ItemMappings.Add(new ItemMapping("Time", DataPointMember.XCategory));
            rc.SeriesMappings.Add(mapping);



            rc.ItemsSource = values;
          

            #endregion;
        }

        private void InitLastMeasured(DataTable table)
        {

            radGridView2.ItemsSource = table;
        }

        private void InitInvalidMeasured(DataTable table)
        {
            List<InvalidMeasuredUser> l = table.AsEnumerable().Select(c =>
                new InvalidMeasuredUser
                {
                    UserId  = c.Field<string>("userid"),
                    UserName = c.Field<string>("username"),
                    Type = c.Field<string>("measureType"),
                    Date = c.Field<string>("measureDate"),
                    Value = c.Field<string>("measureValue"),
                    Max = c.Field<string>("max"),
                    Min = c.Field<string>("min")
                }).ToList();

            List<InvalidMeasuredUser> q = (from i in l
                     group i by new { UserID = i.UserId, Type = i.Type }
                         into grp
                         select new InvalidMeasuredUser
                         {
                             UserId = grp.Key.UserID,
                             Type = grp.Key.Type,
                             Date = grp.Max(c => c.Date)
                         }).ToList();

            List<InvalidMeasuredUser> list = new List<InvalidMeasuredUser>();
            foreach (var i in q)
            {
                list.Add(l.Single(c => c.UserId == i.UserId && c.Type == i.Type && c.Date == i.Date));
            }
            radGridView1.ItemsSource = list;
        }

        private void UserList_click(object sender, RoutedEventArgs e)
        {
            (Application.Current.MainWindow as MainWindow).ContentFrame.Source 
                = new Uri("View/UserPanel.xaml", UriKind.Relative);
        }

        private void AddUser_click(object sender, RoutedEventArgs e)
        {
            UserForm win = new UserForm();
            win.ShowDialog();
        }

        private void DocotrList_click(object sender, RoutedEventArgs e)
        {
            (Application.Current.MainWindow as MainWindow).ContentFrame.Source 
                =  new Uri("View/DoctorPanel.xaml", UriKind.Relative);
        }

        private void AddDoctor_click(object sender, RoutedEventArgs e)
        {
            DoctorForm win = new DoctorForm();
            win.ShowDialog();
        }

        private void Measure_click(object sender, RoutedEventArgs e)
        {
            CardLogin win = new CardLogin((Application.Current.MainWindow as MainWindow).ContentFrame);
            win.ShowDialog();
        }


    }
}
